import cv2
import numpy as np
from control_hardware import send_screen_information_command,wait_screen_command,change_screen_command,not_screen_and_sensor_command
from QR_code import detection_QR_code

change_screen_command('page 7')

cola_num = 0
sprite_num = 0
fanta_num = 0
gum_num = 0
 
LABELS = open("classes.names").read().strip().split("\n")
net = cv2.dnn.readNetFromDarknet('yolov4-tiny.cfg', 'yolov4-tiny_final.weights')
layer = net.getUnconnectedOutLayersNames()

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if ret:
        cv2.imshow("capture", frame)
    k = cv2.waitKey(1)
    if k == ord(' '):
        cv2.imwrite('test.jpg',frame)
        break

cap.release()
cv2.destroyAllWindows()

frame = cv2.imread('test.jpg')
(H, W) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416),swapRB=True, crop=False)
net.setInput(blob)
layerOutputs = net.forward(layer)
boxes = []
confidences = []
classIDs = []
        
for output in layerOutputs:
    for detection in output:
        scores = detection[5:]
        classID = np.argmax(scores)
        confidence = scores[classID]
        box = detection[0:4] * np.array([W, H, W, H])
        (centerX, centerY, width, height) = box.astype("int")
        x = int(centerX - (width / 2))
        y = int(centerY - (height / 2))
        boxes.append([x, y, int(width), int(height)])
        confidences.append(float(confidence))
        classIDs.append(classID)
 
idxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.3)
if len(idxs) > 0:
    for i in idxs.flatten():
        (x, y) = (boxes[i][0], boxes[i][1])
        (w, h) = (boxes[i][2], boxes[i][3])
        text = "{}: {:.4f}".format(LABELS[classIDs[i]], confidences[i])

        if LABELS[classIDs[i]] == 'gum':
            color = (0,0,255)
            gum_num = gum_num + 1
        else:
            color = (0,255,0)
            if LABELS[classIDs[i]] == 'cola':
                cola_num = cola_num + 1
            elif LABELS[classIDs[i]] == 'sprite':
                sprite_num = sprite_num + 1
            elif LABELS[classIDs[i]] == 'fanta':
                fanta_num = fanta_num + 1

        cv2.rectangle(frame, (x, y), (x + w, y + h), color, 1, lineType=cv2.LINE_AA)
        cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,0.5, color, 1, lineType=cv2.LINE_AA)

cv2.imshow('frame',frame)
cv2.waitKey(0)
cv2.destroyAllWindows()

send_screen_information_command('t71.txt',sprite_num)
send_screen_information_command('t72.txt',cola_num)
send_screen_information_command('t73.txt',fanta_num)
send_screen_information_command('t707.txt',gum_num)

retail_sum = sprite_num*3 + cola_num*2 + fanta_num*8 + gum_num*2
send_screen_information_command('t714.txt',retail_sum)
send_screen_information_command('t713.txt',sprite_num+cola_num+fanta_num+gum_num)

wait_screen_command(b'Z1')


cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if ret:
        cv2.imshow("capture", frame)
        barcodeData = detection_QR_code(frame)
    cv2.waitKey(1)
    if barcodeData=='Payment succeeded':
        change_screen_command('page 0')
        not_screen_and_sensor_command('C-!')
        break
                                           
cap.release()
cv2.destroyAllWindows()
